<template>
  <div class="asset-overview-container">
    <h2>资产概览</h2>
    
    <div class="filter-bar">
      <el-date-picker v-model="dateRange" type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="handleDateChange"
      />
      <el-select v-model="deptFilter" placeholder="选择部门" @change="handleFilterChange">
        <el-option label="全部部门" value="" />
        <el-option label="技术部" value="技术部" />
        <el-option label="市场部" value="市场部" />
        <el-option label="行政部" value="行政部" />
        <el-option label="财务部" value="财务部" />
      </el-select>
      <el-button type="primary" @click="refreshData">刷新数据</el-button>
    </div>
    
    <div class="stats-grid">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-label">总资产数量</div>
          <div class="stat-value">{{ statistics.totalAssets || 0 }}</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-label">在用资产</div>
          <div class="stat-value">{{ statistics.inUseAssets || 0 }}</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-label">闲置资产</div>
          <div class="stat-value">{{ statistics.idleAssets || 0 }}</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-label">待报废资产</div>
          <div class="stat-value">{{ statistics.pendingScrapAssets || 0 }}</div>
        </div>
      </el-card>
    </div>
    
    <div class="charts-section">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>资产增长趋势</span>
          </div>
        </template>
        <div id="growthTrendChart" class="chart"></div>
      </el-card>
      
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>资产类型分布</span>
          </div>
        </template>
        <div id="assetTypeChart" class="chart"></div>
      </el-card>
    </div>
    
    <div class="recent-activities">
      <h3>最近资产变动</h3>
      <el-table :data="recentActivities" style="width: 100%">
        <el-table-column prop="assetName" label="资产名称" />
        <el-table-column prop="assetCode" label="资产编号" />
        <el-table-column prop="operation" label="操作类型" />
        <el-table-column prop="operator" label="操作人" />
        <el-table-column prop="operationTime" label="操作时间" />
        <el-table-column prop="remark" label="备注" />
      </el-table>
    </div>
  </div>
</template>



<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { getAssetOverview1API } from '@/api/asset.js'
import { ElMessage } from 'element-plus'

// ==================== 响应式数据 ====================
const dateRange = ref([]) // 日期筛选范围
const deptFilter = ref('') // 部门筛选
// 资产统计数据（动态从后端获取）
const statistics = ref({
  totalAssets: 0,
  inUseAssets: 0,
  idleAssets: 0,
  pendingScrapAssets: 0
})
const recentActivities = ref([]) // 近期操作记录
// 图表实例（非响应式引用，仅存实例）
const growthChart = ref(null)
const typeChart = ref(null)

// ==================== 核心：加载后端数据 ====================
const loadData = async () => {
  try {
    // 处理日期参数（格式化为 YYYY-MM-DD，无日期时传空）
    const startDate = dateRange.value[0]?.toISOString().split('T')[0] || ''
    const endDate = dateRange.value[1]?.toISOString().split('T')[0] || ''

    // 调用后端接口，传入筛选条件
    const res = await selectInfoByDeptNameAndDateAPI({
      deptName: deptFilter.value, // 部门筛选
      startDate: startDate, // 开始日期
      endDate: endDate // 结束日期
    })

    // 假设后端返回格式（根据实际接口调整字段名）
    if (res.code === 200 && res.data) {
      const {
        statistics, // 统计数据（totalAssets、inUseAssets 等）
        recentActivities, // 近期操作记录数组
        growthData, // 增长趋势数据（x轴月份 + y轴数量）
        typeData // 资产类型占比数据
      } = res.data

      // 更新响应式数据
      statistics.value = statistics || { totalAssets: 0, inUseAssets: 0, idleAssets: 0, pendingScrapAssets: 0 }
      recentActivities.value = recentActivities || []

      // 数据更新后刷新图表
      initGrowthTrendChart(growthData)
      initAssetTypeChart(typeData)
    } else {
      // 无数据时重置
      statistics.value = { totalAssets: 0, inUseAssets: 0, idleAssets: 0, pendingScrapAssets: 0 }
      recentActivities.value = []
      resetCharts() // 重置图表为无数据状态
      ElMessage.warning('暂无符合条件的资产数据')
    }
  } catch (error) {
    console.error('加载资产概览数据失败：', error)
    statistics.value = { totalAssets: 0, inUseAssets: 0, idleAssets: 0, pendingScrapAssets: 0 }
    recentActivities.value = []
    resetCharts()
    ElMessage.error('数据加载失败，请重试')
  }
}

// ==================== 图表相关 ====================
// 初始化增长趋势图（接收后端动态数据）
const initGrowthTrendChart = (growthData = {}) => {
  const chartDom = document.getElementById('growthTrendChart')
  if (!chartDom) return

  // 销毁旧实例，避免内存泄漏
  if (growthChart.value) {
    growthChart.value.dispose()
  }

  growthChart.value = echarts.init(chartDom)

  // 处理后端数据（无数据时显示默认值）
  const xData = growthData.xAxis || ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  const seriesData = growthData.series || [1200, 1250, 1280, 1320, 1350, 1400, 1430, 1450, 1480, 1500, 1515, 1528]

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b} <br/>{a}: {c}台'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xData.length > 0 ? xData : ['暂无数据']
    },
    yAxis: {
      type: 'value',
      min: 0
    },
    series: [
      {
        name: '资产总数',
        type: 'line',
        stack: '总量',
        data: seriesData,
        smooth: true,
        lineStyle: { width: 2 }
      }
    ],
    // 无数据提示
    graphic: xData.length === 0 ? [{
      type: 'text',
      left: 'center',
      top: 'center',
      style: { text: '暂无趋势数据', fontSize: 14, fill: '#999' }
    }] : []
  }

  growthChart.value.setOption(option)
}

// 初始化资产类型饼图（接收后端动态数据）
const initAssetTypeChart = (typeData = []) => {
  const chartDom = document.getElementById('assetTypeChart')
  if (!chartDom) return

  // 销毁旧实例
  if (typeChart.value) {
    typeChart.value.dispose()
  }

  typeChart.value = echarts.init(chartDom)

  // 处理后端数据（无数据时显示默认值）
  const pieData = typeData.length > 0 
    ? typeData 
    : [
        { value: 624, name: '电子设备' },
        { value: 328, name: '办公家具' },
        { value: 156, name: '车辆设备' },
        { value: 286, name: '生产设备' },
        { value: 134, name: '其他' }
      ]

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}台 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: pieData.map(item => item.name)
    },
    series: [
      {
        name: '资产类型',
        type: 'pie',
        radius: '50%',
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter: () => pieData.length === 0 ? '暂无数据' : '{b}: {c} ({d}%)'
        }
      }
    ]
  }

  typeChart.value.setOption(option)
}

// 重置图表为无数据状态
const resetCharts = () => {
  initGrowthTrendChart({ xAxis: [], series: [] })
  initAssetTypeChart([])
}

// 图表自适应窗口大小
const handleResize = () => {
  growthChart.value && growthChart.value.resize()
  typeChart.value && typeChart.value.resize()
}

// ==================== 交互方法 ====================
// 日期筛选变化
const handleDateChange = () => {
  refreshData()
}

// 部门筛选变化
const handleFilterChange = () => {
  refreshData()
}

// 刷新数据（筛选条件变化时调用）
const refreshData = () => {
  console.log('刷新数据：', {
    dateRange: dateRange.value,
    deptFilter: deptFilter.value
  })
  loadData() // 重新调用接口加载数据
}

// ==================== 生命周期 ====================
// 组件挂载时加载初始数据
onMounted(() => {
  loadData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时销毁图表+移除事件
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  growthChart.value && growthChart.value.dispose()
  typeChart.value && typeChart.value.dispose()
})
</script>

<style scoped>
.asset-overview-container {
  padding: 20px;
}

.filter-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 30px;
}

.stat-card {
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  text-align: center;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  width: 100%;
  height: 320px;
}

.recent-activities {
  margin-top: 30px;
}

.recent-activities h3 {
  margin-bottom: 15px;
  color: #333;
}
</style>